﻿using System;
using System.IO;
using System.Net;
using System.Web;
//using Storm.Common.Utils.Extensions;

namespace _0512301_0512430.Main
{
    public class GoogleMaps
    {
        private string API_KEY = string.Empty;

        public GoogleMaps(string api_key)
        {
            this.API_KEY = api_key;
        }

        public void SetApiKey(string key)
        {
            this.API_KEY = key;
        }

        /// <summary>
        /// Perform a geocode lookup of an address
        /// </summary>
        /// <param name="addr">The address in CSV form line1, line2, postcode</param>
        /// <param name="output">CSV or XML</param>
        /// <returns>LatLng object</returns>
        public LatLng GetLatLng(string addr)
        {
            string q = Main.frmMain.strFind.ToString();

            q = q.ToLower();
            q = q.Replace(' ', '+');

            var url = "http://maps.google.co.uk/maps/geo?output=csv&key=" +
                       this.API_KEY + "&q="+q;

            var request = WebRequest.Create(url);
            var response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {

                var ms = new MemoryStream();
                var responseStream = response.GetResponseStream();

                var buffer = new Byte[2048];
                int count = responseStream.Read(buffer, 0, buffer.Length);

                while (count > 0)
                {
                    ms.Write(buffer, 0, count);
                    count = responseStream.Read(buffer, 0, buffer.Length);
                }

                responseStream.Close();
                ms.Close();

                var responseBytes = ms.ToArray();
                var encoding = new System.Text.ASCIIEncoding();

                var coords = encoding.GetString(responseBytes);
                var parts = coords.Split(',');

                return new LatLng(
                              Convert.ToDouble(parts[2]),
                              Convert.ToDouble(parts[3]));
            }

            return null;
        }
    }
}